package stdio.costa.imoca.spi;

import java.util.ArrayList;
import java.util.List;

import javax.mail.Message;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import stdio.costa.imoca.model.MocaUser;
import stdio.costa.imoca.notification.email.EmailRecipient;
import stdio.costa.imoca.notification.email.EmailSender;
import stdio.costa.imoca.notification.email.EmailTemplateProcessor;
import stdio.costa.imoca.notification.email.EmailTemplateVariable;

@Component
public class SendForgetPasswordEmailSpi {

	@Value("#{properties['mail.forgetpassword.conent']}")
	private String emailConent;

	@Value("#{properties['mail.forgetpassword.title']}")
	private String emailTitle;

	@Value("#{properties['mail.forgetpassword.expression']}")
	private String passwordAddressExpression;

	@Autowired
	private EmailSender emailSender;

	public void sendEmail(MocaUser user) throws AddressException {

		List<EmailTemplateVariable> variables = this
				.warpEmailTemplateVariables(user);

		String content = EmailTemplateProcessor.process(this.emailConent,
				variables);

		List<EmailRecipient> recipients = this.wrapEmailRecipients(user);

		this.emailSender.sendEmail(recipients, emailTitle, content);

	}

	private List<EmailTemplateVariable> warpEmailTemplateVariables(MocaUser user) {

		List<EmailTemplateVariable> list = new ArrayList<EmailTemplateVariable>();

		list.add(new EmailTemplateVariable(passwordAddressExpression, user
				.getPassword()));

		return list;
	}

	private List<EmailRecipient> wrapEmailRecipients(MocaUser user) throws AddressException {

		List<EmailRecipient> recipients = new ArrayList<EmailRecipient>();

		recipients.add(new EmailRecipient(new InternetAddress(user.getEmail()),
				Message.RecipientType.TO));
		
		return recipients;

	}
}
